package com.czy.seed.mvc.home.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import com.alibaba.fastjson.JSONObject;
import com.czy.seed.mvc.base.controller.BaseController;
import com.czy.seed.mvc.home.entity.*;
import com.czy.seed.mvc.home.service.CommodityService;
import com.czy.seed.mvc.home.service.MenuService;
import com.czy.seed.mvc.home.service.MerchantService;
import com.czy.seed.mvc.sys.entity.SysUser;
import com.czy.seed.mvc.sys.service.SysUserService;
import com.czy.seed.mvc.util.*;
import com.czy.seed.mybatis.base.QueryParams;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/home/merchant")
public class MerchantController extends BaseController<Merchant> {

    @Autowired
    SystemProperties systemProperties;

    private String url = this.getClass().getClassLoader().getResource("").getPath() + "\\" + "static" + "\\" + "lib" + "\\" + "images" + "\\";

    public static Logger logger = LoggerFactory.getLogger(MerchantController.class);

    private String STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private MenuService menuServic;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/insertALL")
    /**插入商家信息*/
    public String insertALL(MultipartHttpServletRequest request) {
        String msg = "";
        try {
            msg = merchantService.insertMerchant(request, url);
            logger.info("成功添加商家信息:{}", request.getParameter("companyName"));
        } catch (Exception e) {
            logger.error("添加商家信息失败");
            msg = "添加商家信息失败";
        }

        return msg;
    }

    /*查询商品信息*/
    @RequestMapping("/selectCommodity")
    public Res selectCommodity(Long businessesId) {
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        QueryParams queryParams = new QueryParams(Commodity.class);
        queryParams.orderBy("install").desc();
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("businessesId", businessesId);
        try {
            List<Commodity> CommodityList = commodityService.selectListByParams(queryParams);
            pageInfo.put("CommodityList", CommodityList);
        } catch (Exception e) {
            logger.error("查询商品信息失败");
        }
        return Res.ok(pageInfo);
    }

    //依据登录ID查询商家信息
    @RequestMapping("/selectMerchantByUserId")
    public Res selectMerchantByUserId() {
        QueryParams queryParams = new QueryParams(Merchant.class);
        QueryParams.Criteria criteria1 = queryParams.createCriteria();
        criteria1.andEqualTo("userId", PrincipalUtil.getLoginUser().getId());
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            Merchant merchant = merchantService.selectOneRelativeByParams(queryParams);
            pageInfo.put("merchant", merchant);
        } catch (Exception e) {
            logger.error("查询商家信息失败",e);
        }
        return Res.ok(pageInfo);

    }

    /*查询商家信息*/
    @RequestMapping("/selectAll")
    public Res selectAll() {
        QueryParams queryParams = new QueryParams(Merchant.class);
        Map<String, Object> pageInfo = new HashMap<String, Object>(16);
        try {
            List<Merchant> merchant = merchantService.selectListByParams(queryParams);
            pageInfo.put("merchant", merchant);
        } catch (Exception e) {
            logger.error("查询商品信息失败");
        }
        return Res.ok(pageInfo);

    }

    /*根据品目编码查询所有商家的信息*/
    @RequestMapping("/selectByPmbm")
    public Res selectByPmbm(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        String goodsType = request.getParameter("goodsType");
        try {
            QueryParams queryParams1 = new QueryParams(Merchant.class);
            QueryParams.Criteria criteria1 = queryParams1.createCriteria();
            criteria1.andLike("goodsType", "%" + goodsType + "%");
            List<Merchant> merchant = merchantService.selectListByParams(queryParams1);
            pageInfo = new HashMap<String, Object>(16);
            pageInfo.put("merchant", merchant);
        } catch (Exception e) {
            logger.error("根据商品大类查询所有关联商家的信息失败");
        }
        return Res.ok(pageInfo);
    }

    /*查看非入围商家信息用于审批*/
    @RequestMapping("/selectNoCut")
    public Res selectNoCut() {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        QueryParams queryParams = new QueryParams(Merchant.class);
        QueryParams.Criteria criteria = queryParams.createCriteria();
        criteria.andEqualTo("type", 0);
        try {
            List<Merchant> merchant = merchantService.selectListRelativeByParams(queryParams);
            pageInfo.put("shopDataList", merchant);
        } catch (Exception e) {
            logger.error("查看非入围商家信息用于审批失败");
        }
        return Res.ok(pageInfo);
    }

    /*查看采购办自己创建采购单位所属的非入围商家信息用于审批
    * 包括商品商家之后也会将商家信息罗列出来 用于审批
    * */
    @RequestMapping("/selectNoCutByCreateUser")
    public Res selectNoCutByCreateUser() {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            List<Merchant> merchant = merchantService.selectMerchant4CreateBy(PrincipalUtil.getLoginUser().getId());
            List<Merchant> merchant_ = new ArrayList<Merchant>();
            for (Merchant mm : merchant) {
                //查询menu
                QueryParams queryParams1 = new QueryParams(Menu.class);
                QueryParams.Criteria criteria1 = queryParams1.createCriteria();
                criteria1.andCondition("id in(" + mm.getGoodsType() + ")");
                List<Menu> menuList = menuServic.selectListByParams(queryParams1);
                int l = 1;
                StringBuffer bf = new StringBuffer();
                for (Menu m : menuList) {
                    if (l == 1) {
                        bf.append(m.getName());
                    } else {
                        bf.append("/");
                        bf.append(m.getName());
                    }
                    l++;
                }
                mm.setGoodsType(bf.toString());
                merchant_.add(mm);
            }
            pageInfo.put("shopDataList", merchant_);
        } catch (Exception e) {
            logger.error("查询采购办创建采购单位所属的非入围商家信息失败");
        }
        return Res.ok(pageInfo);
    }

    /*查看非入围商家的商品信息用于审批*/
    @RequestMapping("/selectNoCutCommodity")
    public Res selectNoCutCommodity(Long id, String type) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            QueryParams queryParams = new QueryParams(Commodity.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("businessesId", id);
            criteria.andCondition("install in(1,2)");
            if ("0".equals(type)) {
                List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
                pageInfo.put("commodityList", commodityList);
                logger.info("查询非入围商家的商品信息成功：" + commodityList.get(0).getCommodityName());
            } else {
                criteria.andLike("commodityName", "%" + type + "%");
                List<Commodity> searchity = commodityService.selectListByParams(queryParams);
                pageInfo.put("searchity", searchity);
                logger.info("模糊查询非入围商家的商品信息成功：" + searchity.get(0).getCommodityName());
            }
        } catch (Exception e) {
            logger.error("查询非入围商家的商品信息失败");
        }
        return Res.ok(pageInfo);
    }

    @RequestMapping("/updateNoCut")
    public Res updateNoCut(HttpServletRequest request) {
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        try {
            pageInfo = merchantService.updateNoCut_impl(request);
        } catch (Exception e) {
            pageInfo.put("message", e.getMessage());
            logger.error("采购办审核商家及其附属商品失败");
        }
        return Res.ok(pageInfo);
    }

    //修改商家信息
    @RequestMapping("/updateSell")
    public String updateSell(MultipartHttpServletRequest request) {
        String message = "";
        String Merchant = request.getParameter("Merchant");
        try {
            Merchant merchant = JSONObject.parseObject(Merchant, Merchant.class);
            //修改User表的商家信息
            SysUser sysUser = sysUserService.selectByPrimaryKey(merchant.getUserId());
            sysUser.setXmname(merchant.getXmname());
            sysUser.setEmail(merchant.getMail());
            sysUser.setEnabled(false);
            sysUser.setTelephone(merchant.getTel());
            sysUser.setUpdateDt(new Date());
            sysUser.setAddress(merchant.getAffiliatedRegional());
            sysUserService.updateByPrimaryKey(sysUser);
            //修改商品信息
            QueryParams queryParams = new QueryParams(Commodity.class);
            QueryParams.Criteria criteria = queryParams.createCriteria();
            criteria.andEqualTo("businessesId", merchant.getId());
            List<Commodity> commodityList = commodityService.selectListByParams(queryParams);
            for (Commodity commodity : commodityList) {
                commodity.setInstall(2);
                commodity.setUpdteTime(new Date());
                commodityService.updateByPrimaryKey(commodity);
            }
            //修改商家信息
            String goodstype = merchant.getGoodsType();
            goodstype = goodstype.replace("[", "").replace("]", "").replace('"', ' ');
            goodstype = goodstype.replace(" ", "");
            merchant.setGoodsType(goodstype);
            File file = new File(url + merchant.getInstitutionCode());
            if (!file.exists()) {
                file.mkdirs();
            }
            String URL = new FilesUpload().Upload("file", file.getCanonicalPath(), request, null);
            merchant.setCompanyLogo("../lib/images/" + merchant.getInstitutionCode() + "/" + URL);
            merchant.setType(0);
            merchant.setUpdateTime(new Date());
            int i = merchantService.updateByPrimaryKey(merchant);
            logger.info("商家信息修改成功:" + merchant.getCompanyName());
            message = "商家信息修改成功!";
        } catch (Exception e) {
            message = "商家信息修改失败!";
            logger.error("商家信息修改失败");
        }
        return message;
    }

    //发送验证码信息
    @RequestMapping("/mailCode")
    public String mailCode(String mail) {
        String code = securityCode();
        //发送的邮件内容

        String message = "您本次操作的验证码为：" + code;
        //发送的邮件地址
        String fromTo = mail;
        //发送的邮件标题
        String subject = "阳光云彩商家入驻信息验证码";
        boolean type = new MailUtil().sendMessage(fromTo, subject, message, systemProperties);
        if (!type) {
            code = "500";
        }
        return code;
    }

    /**
     * 生成随机的四位验证码
     *
     * @return
     */
    /*@Scheduled(cron = "0 0 2 ? * *")*/
    public String securityCode() {
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            char ch = STR.charAt(new Random().nextInt(STR.length()));
            sb.append(ch);
        }
       /* System.out.println("sb:" + sb);*/
        logger.info("==============生成的验证码信息为：{}", sb.toString());
        return sb.toString();


    }

    /**
     * 批量导入商品信息
     *
     * @param
     * @return
     */
    @RequestMapping("/submitUpload")
    public String submitUpload(MultipartHttpServletRequest request) {

        String msg = "";
        //解析excel，
        try {
            Long shopId = Long.parseLong(request.getParameter("id"));
            List<CommodityExcel> commodityList = ExportExcel.importExcel(request.getFile("file"), 3, 1, CommodityExcel.class);
            List<Commodity> commodities = new ArrayList<>();
            for(CommodityExcel commodityExcel:commodityList){
                Commodity commodity = new Commodity();
                commodity.setBusinessesId(shopId);
                commodity.setCommodityName(commodityExcel.getCommodityName());
                commodity.setBrand(commodityExcel.getBrand());
                commodity.setModel(commodityExcel.getModel());
                commodity.setCommodityMakPrc(new BigDecimal(commodityExcel.getMarketPrice()));
                commodity.setCommodityTrcPrc(new BigDecimal(commodityExcel.getAgreementPrice()));
                commodity.setRests(commodityExcel.getIndex());
                commodity.setDiscounts(commodityExcel.getDiscountRate());
                commodity.setInstall(3);
                commodities.add(commodity);
            }
            commodityList.size();
            int i = commodityService.insertList(commodities);
            msg = "Excel解析上传成功！";
        } catch (Exception e) {
            msg = "Excel上传解析失败！";
            logger.error("ECXEL导入商品信息失败！");
        }


        return msg;
    }
}
